import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { connection } from "@/services/database";
import { jwtSecret } from "@/configs/jwt";

interface Params {
	phone_number?: string;
	account?: string;
	password?: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const params = request.body as unknown as Params;
		let user_id = null;
		if (params.phone_number !== void 0) {
			const [results] = (await connection.execute("SELECT user_id, password FROM user WHERE phone_number = :phone_number", params)) as any;
			if (!results[0]) throw new Error("手机号不存在");
			user_id = results[0].user_id;
		}
		if (params.account !== void 0 && params.password !== void 0) {
			const [results] = (await connection.execute("SELECT user_id, password FROM user WHERE password = :password AND (username = :account OR phone_number = :account)", params)) as any;
			if (!results[0]) throw new Error("账号或密码错误");
			user_id = results[0].user_id;
		}
		if (user_id === null) throw new Error("登录失败");
		const token = jwt.sign({ id: user_id }, jwtSecret as string, { expiresIn: "7d" });
		response.json({ data: { token }, message: "成功" });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
